package com.niit.mobileDevide.Gender;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class GenderMapper extends Mapper<LongWritable, Text, Text, Text> {

    // 定义各字段的索引位置
    private static final int GENDER_INDEX = 9; // 性别
    private static final int DEVICE_MODEL_INDEX = 10; // 设备型号

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length < Math.max(GENDER_INDEX, DEVICE_MODEL_INDEX) + 1) { // 确保有足够的字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 使用性别作为key的一部分，并将其映射为"Male"或"Female"
            String genderCode = columns[GENDER_INDEX].trim();
            String gender;
            if ("1".equals(genderCode)) {
                gender = "Male";
            } else if ("2".equals(genderCode)) {
                gender = "Female";
            } else {
                System.err.println("Invalid gender code: " + genderCode + ". Skipping line.");
                return;
            }

            // 获取设备型号并去除前后空白
            String deviceModel = columns[DEVICE_MODEL_INDEX].trim();

            // 输出组合键值对，键是性别和设备型号的组合，值是常量"1"用于计数
            context.write(new Text(gender + "-" + deviceModel), new Text("1"));

        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}